﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Essensoft.AspNetCore.Payment.Alipay.Domain;
using General.Core.Common;
using General.Core.Config;
using General.Entities.Models;
using General.Mvc.Filters;
using General.Services.Admin;
using General.Services.Article;
using General.Services.Authority;
using General.Services.Role;
using General.Services.SystemConfig;
using General.Services.Template;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;

namespace General.Mvc.Controllers.Admin
{
    public class AdminController : Controller
    {
        private readonly IAdminService adminService;
        private readonly IRoleService roleService;
        private readonly ISystemConfigService systemConfigService;
        private readonly IAuthorityService authorityService;
        private readonly ITemplateService templateService;
        private readonly IArticleCateService articleCateService;
        private readonly IArticleService articleService;
        private readonly IMemoryCache memoryCache;

        public AdminController(IAdminService adminService, IRoleService roleService,ISystemConfigService systemConfigService,
            IAuthorityService authorityService,
            ITemplateService templateService,
            IArticleCateService articleCateService,
            IArticleService articleService,
            IMemoryCache memoryCache)
        {
            this.adminService = adminService;
            this.roleService = roleService;
            this.systemConfigService = systemConfigService;
            this.authorityService = authorityService;
            this.templateService = templateService;
            this.articleCateService = articleCateService;
            this.articleService = articleService;
            this.memoryCache = memoryCache;
        }


        /// <summary>
        /// 默认路由跳转
        /// </summary>
        /// <returns></returns>
        [HttpGet("/Admin")]
        public IActionResult Jump() 
        {
            return Redirect("/Admin/Index");
        }


        /// <summary>
        /// 后台首页
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ServiceFilter(typeof(AdminCheckFilter))]
        public async Task<IActionResult> Index()
        {
            //获取用户信息
            var user = JsonHelper.Deserialize<tc_admin>(HttpContext.Session.GetString("Admin"));
            var model = await adminService.GetInfoById(user.id);
            var authorityList = await authorityService.GetIsUseData();
            var userRoleId = user.role.Split(",", StringSplitOptions.RemoveEmptyEntries).Select<string, int>(x => Convert.ToInt32(x)).ToList();
            var roleList = JsonHelper.Deserialize<List<tc_role>>(memoryCache.Get(GobalConfig.SYSTEM_ROLELISTMEMORYKEY_STRING).ToString());
            var adminRoleList = roleList.Where(x => userRoleId.Contains(x.id)).ToList();
            var permissionList = new List<int>();
            foreach (var item in adminRoleList)
            {
                permissionList.AddRange(item.permission.Split(",", StringSplitOptions.RemoveEmptyEntries).Select<string, int>(x => Convert.ToInt32(x)).ToList());
            };


            //如果为管理员所有页面可访问
            if (adminRoleList.Where(x => x.rolecode == "admin").FirstOrDefault() != null)
            {
                ViewBag.authorityList = authorityList.ToList();
            }
            else
            {
                ViewBag.authorityList = authorityList.Where(x => permissionList.Contains(Convert.ToInt32(x.id))).ToList();
            }
            
            return View(model);
        }


        /// <summary>
        /// 通知消息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("/Admin/page/tpl/tpl-message.html")]
        [ServiceFilter(typeof(AdminCheckFilter))]
        public IActionResult Tpl_Message()
        {
            return View();
        }


        /// <summary>
        /// 本地便签
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("/Admin/page/tpl/tpl-note.html")]
        [ServiceFilter(typeof(AdminCheckFilter))]
        public IActionResult Tpl_Note()
        {
            return View();
        }


        /// <summary>
        /// 锁屏
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("/Admin/page/tpl/tpl-lock-screen.html")]
        [ServiceFilter(typeof(AdminCheckFilter))]
        public async Task<IActionResult> Tpl_Lock_Screen()
        {
            var user = JsonHelper.Deserialize<tc_admin>(HttpContext.Session.GetString("Admin"));
            var model = await adminService.GetInfoById(user.id);
            return View(model);
        }


        /// <summary>
        /// 修改密码
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("/Admin/page/tpl/tpl-password.html")]
        [ServiceFilter(typeof(AdminCheckFilter))]
        public async Task<IActionResult> Tpl_UpdatePassword()
        {
            return View();
        }


        /// <summary>
        /// 皮肤设置
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("/Admin/page/tpl/tpl-theme.html")]
        [ServiceFilter(typeof(AdminCheckFilter))]
        public async Task<IActionResult> Tpl_Theme()
        {
            return View();
        }

        /// <summary>
        /// 个人中心
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ServiceFilter(typeof(AdminCheckFilter))]
        public async Task<IActionResult> User_Info()
        {
            var user = JsonHelper.Deserialize<tc_admin>(HttpContext.Session.GetString("Admin"));
            var model = await adminService.GetInfoById(user.id);
            ViewBag.rolelist = await roleService.GetListByIds(model.role ?? "");
            return View(model);
        }

        /// <summary>
        /// 工作台
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ServiceFilter(typeof(AdminCheckFilter))]
        public async Task<IActionResult> WorkPlace()
        {
            //系统架构
            ViewBag.OSArchitecture = RuntimeInformation.OSArchitecture.ToString();
            //系统名称
            ViewBag.OSDescription = RuntimeInformation.OSDescription.ToString();
            //进程架构
            ViewBag.ProcessArchitecture = RuntimeInformation.ProcessArchitecture.ToString();
            //.netcore版本
            ViewBag.FrameworkDescription = RuntimeInformation.FrameworkDescription;
            var proc = Process.GetCurrentProcess();
            var mem = proc.WorkingSet64;
            var cpu = proc.TotalProcessorTime;
            //进程已使用物理内存(kb)
            ViewBag.UsedMem = mem / 1024.0;
            //进程已占耗CPU时间(ms)
            ViewBag.UsedCPUTime = cpu.TotalMilliseconds;
            //处理器数
            ViewBag.ProcessorCount = Environment.ProcessorCount;


            var todayDate = DateTime.Today;
            ViewBag.TodayUserCount = await adminService.GetCountByDate(todayDate);
            ViewBag.AllUserCount = await adminService.GetCountByDate(null);
            ViewBag.TodayArticleCount = await articleService.GetCountByDate(todayDate);
            ViewBag.AllArticleCount = await articleService.GetCountByDate(null);
            
            return View();
        }


        /// <summary>
        /// 控制台
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ServiceFilter(typeof(AdminCheckFilter))]
        public IActionResult Console()
        {
            return View();
        }

        /// <summary>
        /// 分析页
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ServiceFilter(typeof(AdminCheckFilter))]
        public IActionResult DashBoard()
        {
            return View();
        }

        /// <summary>
        /// 系统设置
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ServiceFilter(typeof(AdminCheckFilter))]
        public async Task<IActionResult> SystemConfig()
        {
            ViewBag.typeList = await systemConfigService.GetTypeList();
            ViewBag.configList = await systemConfigService.GetAllConfigInfo();
            return View();
        }

        /// <summary>
        /// 系统日志
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ServiceFilter(typeof(AdminCheckFilter))]
        public IActionResult LogRecord()
        {
            return View();
        }

        /// <summary>
        /// 定时任务
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ServiceFilter(typeof(AdminCheckFilter))]
        public IActionResult JobList()
        {
            return View();
        }


        /// <summary>
        /// 角色管理
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ServiceFilter(typeof(AdminCheckFilter))]
        public IActionResult RoleList()
        {
            return View();
        }

        /// <summary>
        /// 字典管理
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ServiceFilter(typeof(AdminCheckFilter))]
        public IActionResult Dictionary()
        {
            return View();
        }

        /// <summary>
        /// 区域管理
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ServiceFilter(typeof(AdminCheckFilter))]
        public IActionResult RegionList()
        {
            return View();
        }

        /// <summary>
        /// 管理员列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ServiceFilter(typeof(AdminCheckFilter))]
        public IActionResult AdminList()
        {
            return View();
        }


        /// <summary>
        /// 本地文件
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ServiceFilter(typeof(AdminCheckFilter))]
        public IActionResult MyFiles()
        {
            return View();
        }

        /// <summary>
        /// 代码生成
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ServiceFilter(typeof(AdminCheckFilter))]
        public IActionResult CodeGeneration()
        {
            return View();
        }

        /// <summary>
        /// 权限管理
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ServiceFilter(typeof(AdminCheckFilter))]
        public IActionResult AuthorityList()
        {
            return View();
        }

        
        /// <summary>
        /// 网站导航管理
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ServiceFilter(typeof(AdminCheckFilter))]
        public IActionResult NavigationList()
        {
            return View();
        }

        /// <summary>
        /// 图片轮播管理
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ServiceFilter(typeof(AdminCheckFilter))]
        public IActionResult SliderList()
        {
            return View();
        }


        /// <summary>
        /// 模板管理
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ServiceFilter(typeof(AdminCheckFilter))]
        public IActionResult TemplateList()
        {
            ViewBag.TemplateList = templateService.GetTemplateList();

            return View();
        }


        /// <summary>
        /// 自定义页面管理
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ServiceFilter(typeof(AdminCheckFilter))]
        public IActionResult DiyPageList()
        {
            return View();
        }

        /// <summary>
        /// 友情链接管理
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ServiceFilter(typeof(AdminCheckFilter))]
        public IActionResult LinkList()
        {
            return View();
        }

        /// <summary>
        /// 文章类别管理
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ServiceFilter(typeof(AdminCheckFilter))]
        public IActionResult ArticleCate()
        {
            return View();
        }

        /// <summary>
        /// 文章信息管理
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ServiceFilter(typeof(AdminCheckFilter))]
        public async Task<IActionResult> ArticleList()
        {
            var data = await articleCateService.GetListBySort();
            return View(data);
        }

        /// <summary>
        /// 清除缓存
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ServiceFilter(typeof(AdminCheckFilter))]
        public IActionResult ClearCache()
        {
            return View();
        }




        /// <summary>
        /// 网站地图
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ServiceFilter(typeof(AdminCheckFilter))]
        public IActionResult SiteMap()
        {
            var url = memoryCache.Get("WebSite_Url");
            return View(url);
        }


        /// <summary>
        /// 组织机构管理
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ServiceFilter(typeof(AdminCheckFilter))]
        public IActionResult Organization()
        {
            return View();
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Login()
        {
            return View();
        }






        /// <summary>
        /// 快捷登录
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Galigeigei()
        {
            tc_admin tc_Admin = new tc_admin()
            {
                 createtime = DateTime.Now, id = 1, lastip = "", lasttime = DateTime.Now, password = "e10adc3949ba59abbe56e057f20f883e",nickname = "超级管理员", role = "1", status = 1, username = "admin", headimg= "/images/user.png"
            };
            HttpContext.Session.SetString("Admin", JsonHelper.Serialize(tc_Admin));
            return Redirect("/Admin/Index");
        }
    }
}